using System;
using System.Collections.Generic;
using System.Net;
using System.Text;
using CodePlex.TfsLibrary.ObjectModel;

namespace CodePlex.UnitTestUtility
{
    public class StubWebTransferService : IWebTransferService
    {
        public Dictionary<string, string> Download__FilesDownloaded = new Dictionary<string, string>();
        public string Download__Text = null;
        public bool Download__ThrowsException = false;
        public ICredentials Download_Credentials;
        public string Download_Url;
        readonly MockFileSystem fileSystem;
        public ICredentials PostForm_Credentials;
        public WebTransferFormData PostForm_FormData;
        public string PostForm_Url;

        public StubWebTransferService(MockFileSystem fileSystem)
        {
            this.fileSystem = fileSystem;
        }

        public WebTransferFormData CreateFormPostData()
        {
            return new WebTransferFormData(fileSystem);
        }

        public void Download(string url,
                             ICredentials credentials,
                             string localPath)
        {
            Download__FilesDownloaded.Add(url, localPath);

            fileSystem.EnsurePath(fileSystem.GetDirectoryName(localPath));
            fileSystem.WriteAllBytes(localPath, DownloadBytes(url, credentials));
        }

        public byte[] DownloadBytes(string url,
                                    ICredentials credentials)
        {
            Download_Url = url;
            Download_Credentials = credentials;

            if (Download__ThrowsException)
                throw new WebException("fooble");

            return Encoding.UTF8.GetBytes(Download__Text ?? "Downloaded from " + url);
        }

        public IAsyncResult BeginDownloadBytes(string url, ICredentials credentials, AsyncCallback callback)
        {
            throw new NotImplementedException();
        }

        public byte[] EndDownloadBytes(IAsyncResult ar)
        {
            throw new NotImplementedException();
        }

        public void PostForm(string url,
                             ICredentials credentials,
                             WebTransferFormData formData)
        {
            PostForm_Url = url;
            PostForm_Credentials = credentials;
            PostForm_FormData = formData;
        }
    }
}
